package com.loiane.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.loiane.model.Tipo;
import com.loiane.service.TipoService;

@Controller
public class TipoController {

	private TipoService tipoService;

	@RequestMapping(value = "/tipo/view.action")
	public @ResponseBody
	Map<String, ? extends Object> view() throws Exception {
		
		try {
			System.out.println("se va a leer ... ");
			List<Tipo> tipos = tipoService.getTipoList();
			System.out.println("se leyooo ... supuestamente");
			return getMapTipo(tipos);

		} catch (Exception e) {
			e.printStackTrace();
			return getModelMapError("Error retrieving Tipos from database.");
		}
	}
	
	@RequestMapping(value = "/tipo/create.action")
	public @ResponseBody
	Map<String, ? extends Object> create(@RequestParam Object data)
			throws Exception {

		try {

			List<Tipo> tipos = tipoService.create(data);

			return getMapTipo(tipos);

		} catch (Exception e) {

			return getModelMapError("Error trying to create contact.");
		}
	}
	
	@RequestMapping(value = "/tipo/update.action")
	public @ResponseBody
	Map<String, ? extends Object> update(@RequestParam Object data)
			throws Exception {
		try {

			List<Tipo> tipos = tipoService.update(data);

			return getMapTipo(tipos);

		} catch (Exception e) {

			return getModelMapError("Error trying to update contact.");
		}
	}
	
	@RequestMapping(value = "/tipo/delete.action")
	public @ResponseBody
	Map<String, ? extends Object> delete(@RequestParam Object data)
			throws Exception {

		try {

			tipoService.delete(data);

			Map<String, Object> modelMap = new HashMap<String, Object>(3);
			modelMap.put("success", true);

			return modelMap;

		} catch (Exception e) {

			return getModelMapError("Error trying to delete contact.");
		}
	}
	
	private Map<String, Object> getMapTipo(List<Tipo> tipos) {

		Map<String, Object> modelMap = new HashMap<String, Object>(3);
		modelMap.put("total", tipos.size());
		modelMap.put("data", tipos);
		modelMap.put("success", true);

		return modelMap;
	}
	
	private Map<String, Object> getModelMapError(String msg) {

		Map<String, Object> modelMap = new HashMap<String, Object>(2);
		modelMap.put("message", msg);
		modelMap.put("success", false);

		return modelMap;
	}

	@Autowired
	public void setTipoService(TipoService tipoService) {
		this.tipoService = tipoService;
	}
	
	
	
}
